package concurrent.threadPool;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * newFixedThreadPool、newSingleThreadExecutor 的任务队列长度最大可以保存Integer.MAX_VALUE个，会造成OOM
 * newCachedThreadPool、newScheduledThreadPool当突然有大量的任务提交过来时，会瞬间创建大量线程导致OOM
 */
public class ExecutorsTest {
	
	public static int i = 0;

	/**
	 * 测试线程池的任务执行顺序
	 */
	public static void main(String[] args) {
		
//		final ThreadPoolExecutor service = (ThreadPoolExecutor)Executors.newFixedThreadPool(4);
//		final ThreadPoolExecutor service = (ThreadPoolExecutor)Executors.newCachedThreadPool();
		final ThreadPoolExecutor service = (ThreadPoolExecutor)Executors.newSingleThreadExecutor();
		for (int i = 0; i < 10000000; i++) {
			final int index = i;
			service.execute(() -> {
				System.out.printf("线程：%d开始执行\n", index);
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.printf("线程：%d结束执行\n", index);
			});
		}
	}
	
}
